import { AssetInfo } from "../@types/packages/asset-db/@types/public";
import fs from "fs";
import { getCodes } from "country-list";
import { sep } from "path";

const country_codes = getCodes();

function collect_folders(path: string, folders: Set<string>) {
    let dirents = fs.readdirSync(path, { withFileTypes: true });
    dirents.forEach(dirent => {
        if (dirent.isDirectory()) {
            collect_folders(`${path}${sep}${dirent.name}`, folders);
        } else {
            folders.add(path);
        }
    });
}

export function onAssetMenu(assetInfo: AssetInfo) {
    return [
      {
        label: '构建资源本地化',
        click() {
          if (!assetInfo) {
            console.log('执行本地化操作失败');
          } else {
            console.log('开始执行本地化操作');
            let current_path = `${assetInfo.file}`;
            let folders = new Set<string>();
            collect_folders(current_path, folders);
            let l10n_folders = Array.from(folders).filter(v => {
                return country_codes.some(code => {
                    return v.includes(`${sep}${code}`);
                });
            });
            let l10n_json = JSON.parse("{}");
            let l10n_codes = new Set();
            l10n_folders.forEach(v => {
                let dirents = fs.readdirSync(v, { withFileTypes: true });
                dirents.forEach(dirent => {
                    if (dirent.isFile() && dirent.name.includes(".meta")) {
                        let file_text = fs.readFileSync(`${v}${sep}${dirent.name}`, { encoding: "utf-8" });
                        let file_json = JSON.parse(file_text);
                        let l10n_code = country_codes.filter(code => v.includes(`${sep}${code}`))[0];
                        let file_name = `${v}${sep}${dirent.name}`.replace(".meta", "").match(`\\${sep}assets\\${sep}(.*)`)?.[0];
                        l10n_json[file_json["uuid"]] = `${file_name}@${l10n_code}`;
                        l10n_codes.add(l10n_code);
                    }
                });
            });
            l10n_json["l10n_country_codes"] = Array.from(l10n_codes);
            fs.writeFileSync(`${current_path}${sep}${assetInfo.name}_l10n.json`, JSON.stringify(l10n_json, null, 2), "utf8");
            console.log(`结束执行本地化操作, 输出文件名为：${assetInfo.name}_l10n.json`);
          }
        },
      },
    ];
};